package Controller;

import DAO.JavaChapterDao;
import com.google.gson.Gson;
import entity.JavaChapter;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

@WebServlet(name = "javaInfoController", value = "/javaInfoController")
public class javaInfoController extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String number = request.getParameter("number");
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json;charset=utf-8");

        PrintWriter out = response.getWriter();
//        response.setContentType("text/html");
//        response.setHeader("Content-type", "text/html;charset=UTF-8");

        JavaChapterDao javaChapterDao = new JavaChapterDao();

        JavaChapter javaChapter = javaChapterDao.queryByNumber(Integer.parseInt(number));

//        String fileName = "D:\\IdeaProjects\\Study_Station\\src\\main\\resources\\" + javaChapter.getTitle();
        String fileName = "E:\\Code\\Java\\Study_Station\\src\\main\\resources\\" + javaChapter.getTitle();

        File file = new File(fileName);

        try {
            FileInputStream inputStream = new FileInputStream(file);
            //定义byte数组
            byte[] bytes = new byte[inputStream.available()];

            int num = 0;
            //定义一个StringBuilder来进行读存
            StringBuilder sb = new StringBuilder();
            //根据文件大小获取相应数量
            char[] chars = new char[inputStream.available()];
            //进入循环 只要num == -1 那就是读取结束了
            while( (num = inputStream.read(bytes)) != -1){
                //可以直接用String(byte[] byte)的构造方法来读取
                String resultText = new String(bytes,"utf-8");
                sb.append(resultText);
            }

            Map<String, Object> map = new HashMap<>();

            map.put("msg","ok");

            map.put("number",number);
            map.put("content", sb.toString());
            System.out.println("map完成");

            String json = new Gson().toJson(map);

            System.out.println("json转换完成");

            out.print(json);

            System.out.println("what");
            System.out.println("字符串：" + sb.toString());
            inputStream.close();
            out.flush();
            out.close();
        }catch (IOException e) {
            e.printStackTrace();
        }

//        out.println("<!DOCTYPE html>\n"+sb.);

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}
